package alijk.dataView.utils;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.xml.bind.marshaller.CharacterEscapeHandler;

import alijk.dataView.model.RequestBean;
import alijk.dataView.model.ResponseBean;

public class JavaBeanUtils {
	public static final Logger logger = LoggerFactory
			.getLogger(JavaBeanUtils.class);
	public static String convertToXml(Object obj) {  
		return convertToXml(obj,"UTF-8");
	}
	/**
	 * 将javaBean 转成XML
	 * @param obj
	 * @param encoding
	 * @return
	 */
	private static String convertToXml(Object obj, String encoding){
		String result = null;
		try {
			JAXBContext jc = JAXBContext.newInstance(obj.getClass());
			Marshaller m = jc.createMarshaller();
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			m.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() {
				
				@Override
				public void escape(char[] arg0, int arg1, int arg2, boolean arg3,
						Writer arg4) throws IOException {
					arg4.write(arg0, arg1, arg2);
				}
			});
			
			StringWriter writer = new StringWriter();
			m.marshal(obj, writer);
			result = writer.toString();
		} catch (Exception e) {
			logger.info("convertToXml Exception:"+result);
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * xml转换成JavaBean
	 * @param xml
	 * @param c
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T converyToJavaBean(String xml, Class<T> c) {
		T t = null;
		try {
			JAXBContext context = JAXBContext.newInstance(c);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			t = (T) unmarshaller.unmarshal(new StringReader(xml));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return t;
	}
	/**
	 * 得回复信息
	 * @param reqBean
	 * @param content
	 * @return
	 */
	public static String getResponseXml(RequestBean reqBean,String content){
		ResponseBean respBean = new ResponseBean();
		respBean.setFromUserName(reqBean.getToUserName());
		respBean.setToUserName(reqBean.getFromUserName());
		respBean.setMsgType("text");
		respBean.setCreateTime(new Date().getTime());
		respBean.setContent(content);
		return convertToXml(respBean);
	}
}
